package com.imooc.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by 半仙.
 */

@RestController
@Slf4j
public class Controller {

    /**
     * 简单的负载均衡器，不需要声明
     * 帮我们从注册中心拉取到的服务列表中挑选一个可用的service Provide（服务提供者）
     */
    @Autowired
    private LoadBalancerClient client;

    /**
     * 这份方法需要在启动类中声明一下，不然拿不到
     */
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello() {
        // 拿到服务提供者的实例，eureka-client：服务名称
        ServiceInstance instance = client.choose("eureka-client");

        if (instance == null) {
            return "No available instances";
        }

        // 访问的地址
        String target = String.format("http://%s:%s/sayHi",
                instance.getHost(),
                instance.getPort());
        log.info("url is {}", target);

        return restTemplate.getForObject(target, String.class);
    }

    @PostMapping("/hello")
    public Friend helloPost() {
        ServiceInstance instance = client.choose("eureka-client");

        if (instance == null) {
            return null;
        }

        String target = String.format("http://%s:%s/sayHi",
                instance.getHost(),
                instance.getPort());
        log.info("url is {}", target);

        Friend friend = new Friend();
        friend.setName("Eureka Consumer");

        return restTemplate.postForObject(target, friend, Friend.class);
    }

}
